import random
import re
import time
import requests
import feishu_bitable_v2

SHOP_ID = 212434581
feishu_bitable_v2.APP_TOKEN = 'PQmYbkcTqalLl2slp6TcW3TsnVc'
feishu_bitable_v2.TABLE_ID = 'tbl9ZDLzxLMQnuQO'

cookies = {
    'bos.h5.session': 's%3AKXtkKlA-ZEu2501Epi2sGKtd3fk5bKbm.CmjGfoK3uaPKgrjz1n82wluOx8GvWaYeXyhtPzRAZu8',
    'rprm_cuid_time': str(int(time.time() * 1000)),
    'rprm_cuid': '456304613kmlc0ci0a4g',
    'rprm_uuid': '456304613kmlc0ci0a4g',
    'rprm_appShowId2': '-mb04gf27evi8m6cqvml',
    'rprm_session_id': ''
}

# 25春
json_data = {
    "extendParameter": {
        "sceneId": "",
        "sceneType": "",
        "tsoTicket": "",
        "wmkTicket": ""
    },
    "basicInfo": {
        "vid": 6013502443581,
        "vidType": 10,
        "bosId": 4019927749581,
        "productId": 145,
        "productInstanceId": 6741960581,
        "productVersionId": 1,
        "merchantId": 2000069147581,
        "cid": SHOP_ID,
        "tcode": "weimob"
    },
    "extendInfo": {
        "source": 2,
        "youshu": {
            "token": "tokenStr",
            "enable": True
        },
        "refer": "cms-search-result",
        "deviceInfo": {
            "osType": 2
        },
        "channelsource": 5
    },
    "templateId": 18,
    "queryParameter": {
        "goodsClassifyId": 0,
        "goodsClassifyName": "全部商品",
        "search": "25春",
        "sortBySearch": 0,
        "searchType": 5,
        "sortByRule": 1,
        "propSearchInfoList": [],
        "minSalePrice": "",
        "maxSalePrice": "",
        "latitude": "",
        "longitude": "",
        "recentSearchVidId": "",
        "brandId": "",
        "livePriceParam": {}
    },
    "i18n": {
        "language": "zh",
        "timezone": "8"
    },
    "orderBy": [
        {
            "field": "complex",
            "sort": "desc"
        }
    ],
    "pageNum": 1,
    "pageSize": 10
}

json_data_info = {
    "refer": "ec-goods-detail",
    "extendParameter": {
        "sceneId": "",
        "sceneType": "",
        "tsoTicket": "",
        "wmkTicket": ""
    },
    "basicInfo": {
        "vid": 6013502443581,
        "vidType": 10,
        "bosId": 4019927749581,
        "productId": 145,
        "productInstanceId": 6741960581,
        "productVersionId": "12010",
        "merchantId": 2000069147581,
        "cid": 212434581,
        "tcode": "weimob"
    },
    "extendInfo": {
        "source": 2,
        "youshu": {
            "token": "tokenStr",
            "enable": True
        },
        "refer": "ec-goods-detail",
        "deviceInfo": {
            "osType": 2
        },
        "channelsource": 5
    },
    "templateId": 20,
    "queryParameter": {
        "livePriceParam": {
            "livePriceId": "",
            "livePriceType": ""
        },
        "goodsId": 133355275754581,
        "bizCode": "",
        "activityId": "",
        "activityType": "",
        "extParameter": {}
    },
    "i18n": {
        "language": "zh",
        "timezone": "8"
    },
    "bizVid": 6013502443581
}


def getGoodsList(pageNum=1, pageSize=10):
    json_data["pageNum"] = pageNum
    json_data["pageSize"] = pageSize
    print('POST', f'https://{SHOP_ID}.shop.n.weimob.com/api3/mall/navigation/goods/getGoodsList')
    response = requests.post(
        f'https://{SHOP_ID}.shop.n.weimob.com/api3/mall/navigation/goods/getGoodsList',
        cookies=cookies,
        json=json_data,
    )
    if response.status_code != 200:
        print('getGoodsList error', response.status_code, response.text)
        return None
    else:
        return response.json()

def getSkuInfo(goodsId):
    json_data_info["queryParameter"]["goodsId"] = goodsId
    print('POST', f'https://{SHOP_ID}.shop.n.weimob.com/api3/mall/navigation/goods/v3/skuInfo')
    response = requests.post(
        f'https://{SHOP_ID}.shop.n.weimob.com/api3/mall/navigation/goods/v3/skuInfo',
        cookies=cookies,
        json=json_data_info,
    )
    if response.status_code != 200:
        print('getSkuInfo error', response.status_code, response.text)
        return None
    else:
        return response.json()

def get_product_code(title, goods_id):
    # 提取商品标题中的商品编码
    pattern = r'([A-Za-z\d]{6,11})'
    match = re.search(pattern, title)
    return match.group(0) if match else goods_id

def sleep_random():
    random_value = random.uniform(1, 2.5)
    print(f"等待{random_value:.2f}s ...")
    time.sleep(random_value)

if __name__ == '__main__':
    goods_list = getGoodsList()
    if goods_list and goods_list['errcode'] == '0':
        # 获取商品列表个数
        total_count = goods_list['data']['paginationData']['totalCount']
        # 计算需要获取的总页数，每页50个商品
        total_pages = (total_count + 49) // 50  # 向上取整

        sleep_random()

        # 获取剩余商品列表，pageSize不超过50
        for pageNum in range(1, total_pages + 1):
        # for pageNum in range(1, 2):
            records = []
            goods_list = getGoodsList(pageNum=pageNum, pageSize=50)
            sleep_random()

            if goods_list and goods_list['errcode'] == '0':
                goods_data = goods_list['data']['paginationData']['pageList']
                for goods in goods_data:
                    goods_id = goods['id']
                    # 根据商品ID判断是否已添加
                    # if is_goods_added(goods_id):
                    #     print(f"商品ID: {goods_id} 已添加")
                    #     continue

                    print(f"商品ID: {goods_id}")

                    sku_info_data = getSkuInfo(goods_id)['data']
                    if not sku_info_data:
                        print(f"获取商品详情失败, 商品ID: {goods_id}")
                        continue
                    title = sku_info_data['title'].replace('｜', '-')
                    if '24' in title:
                        # 跳过24年的商品
                        print(f"跳过24年商品: {title}")
                        continue

                    product_code = get_product_code(title, str(goods_id))
                    skip_codes = []
                    if product_code in skip_codes:
                        print(f"跳过指定货号商品: {product_code}")
                        continue
                    origin_price = sku_info_data['prices']['maxDeletePrice']['value'] or sku_info_data['prices']['maxSpuPrice']['value'] or sku_info_data['prices']['showPrice']['value']
                    category = sku_info_data['categoryTree']['categoryName'] + '/' + sku_info_data['categoryTree']['childrenCategory']['categoryName']
                    goodsImgUrl = sku_info_data['goodsImgUrl']
                    skuNames = ["颜色","尺码"]
                    skuInfos = sku_info_data['skuInfos']
                    skuInfos = sorted(skuInfos, key=lambda x: skuNames.index(x['name']))
                    specs = []
                    specs_images = []

                    # 从skuInfos中获取颜色属性
                    color_attr = next(attr for attr in skuInfos if attr['name'] == '颜色')
                    # 从skuValueVos中构建颜色ID与图片URL的映射
                    color_image_map = {}
                    for sku in sku_info_data['skuValueVos']:
                        for attr_id, value_id in sku['skuInfoMap'].items():
                            if str(attr_id) == str(color_attr['attributeId']):  # 确保类型一致
                                # 检查value_id是否在颜色属性的attrValueList.key中
                                color_value = next(
                                    (value for value in color_attr['attrValueList'] 
                                    if str(value['key']) == str(value_id)),
                                    None
                                )
                                if color_value and str(value_id) not in color_image_map and sku.get('imageUrl'):
                                    color_image_map[str(value_id)] = sku['imageUrl']
                    # print(f"颜色图片映射: {color_image_map}")

                    if len(skuInfos) > 1:
                        for attr in skuInfos:
                            attr_name = attr['name']
                            attr_values = [value['value'] for value in attr['attrValueList'] 
                                        if not '批次' in value['value']]
                            specs.append({
                                "name": attr_name,
                                "values": attr_values
                            })
                            
                            # 处理颜色属性图片映射
                            specs_images.extend(
                                {
                                    "type": value['value'],
                                    "image_url": value['attrImgUrl'] or color_image_map.get(value['key'])
                                }
                                for value in attr['attrValueList']
                                if (not '批次' in value['value'] and 
                                    not any(v['type'] == value['value'] for v in specs_images) and
                                    (value['attrImgUrl'] or color_image_map.get(value['key'])))
                            )
                    else:
                        print("商品规格不满足要求", skuInfos)

                    print(f"商品ID: {goods_id}, 标题: {title}, 货号：{product_code}, 原价: {origin_price}, 分类: {category}, 图片: {goodsImgUrl}, 规格：{specs}, 规格图片：{specs_images}")
                    # sleep_random()

                    file_path = feishu_bitable_v2.download_image(goodsImgUrl)
                    file_token = feishu_bitable_v2.upload_media(file_path)

                    records.append({
                        "fields": {
                            "货号": product_code,
                            "商品ID": str(goods_id),
                            "商品名称": title,
                            "划线价(元)": origin_price,
                            "分类": category,
                            "商品图片": [{"file_token": file_token}],
                            "商品图片链接": {
                                "link": goodsImgUrl,
                                "text": goodsImgUrl
                            },
                            # "商品图片本地路径": file_path,
                            "商品规格1-名称": specs[0]['name'] if len(specs) > 0 else None,
                            "商品规格1-值": ",".join(specs[0]['values']) if len(specs) > 0 and specs[0]['values'] else None,
                            # "商品规格1-图片": [{"file_token": v["file_token"]} for v in specs_images if v["file_token"]],
                            "商品规格1-图片链接": ",".join([v["image_url"] for v in specs_images if v["image_url"]]),
                            # "商品规格1-图片本地路径": ",".join([v["file_path"] for v in specs_images if v["file_path"]]),
                            "商品规格2-名称": specs[1]['name'] if len(specs) > 1 else None,
                            "商品规格2-值": ",".join(specs[1]['values']) if len(specs) > 1 and specs[1]['values'] else None,
                        }
                    })
                    
            if records and len(records) > 0:
                print(f"新增 {len(records)} 商品记录...")
                # 每次最多上传1000条
                batch_size = 1000
                for i in range(0, len(records), batch_size):
                    batch_records = records[i:i + batch_size]
                    if feishu_bitable_v2.batch_create_records(batch_records):
                        print(f"新增商品记录 {len(batch_records)} 条成功")
                    else:
                        print("新增商品记录失败")
            else:
                print("没有需要新增的商品记录")

    else:
        print("获取商品列表失败")
        
    input("按任意键退出...")
